﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Serviio.API;

namespace Serviio.WHS2011
{
    public partial class StatusTabControl : UserControl
    {
        private static readonly LogFacade log = LogFacade.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public StatusTabControl()
        {
            InitializeComponent();
            try
            {
                labelScanLastAdded.Text = "";
                labelScanNumAdded.Text = "";

                imageList16.Images.Add("RED", Properties.Resources.Red16);
                imageList16.Images.Add("GREEN", Properties.Resources.Green16);
                
                imageList32.Images.Add("GENERIC", Properties.Resources.Device);
                imageList32.Images.Add("ACTIVE", Properties.Resources.Green32);
                imageList32.Images.Add("INACTIVE", Properties.Resources.Red32);
                imageList32.Images.Add("UNKNOWN", Properties.Resources.White32);

                imageList48.Images.Add(Properties.Resources.LibraryIdle);
                imageList48.Images.Add(Properties.Resources.LibraryScan1);
                imageList48.Images.Add(Properties.Resources.LibraryScan2);
                imageList48.Images.Add(Properties.Resources.LibraryScan3);
                imageList48.Images.Add(Properties.Resources.LibraryScan4);
                imageList48.Images.Add(Properties.Resources.LibraryScan5);
                imageList48.Images.Add(Properties.Resources.LibraryScan6);
                imageList48.Images.Add(Properties.Resources.LibraryScan7);
                imageList48.Images.Add(Properties.Resources.LibraryScan8);

                colDevice.ImageGetter = delegate(object row)
                {
                    return "GENERIC";
                };
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private ServiioConnection conn = null;

        public void Initialize(ServiioConnection connection)
        {
            try
            {
                if (this.conn != null)
                    return;

                log.Info("Initializing...");

                this.conn = connection;

                PopulateDevices();

                timerLibraryStatus.Enabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void RefreshDevices()
        {
            try
            {
                if (conn == null)
                    return;

                conn.Status.Refresh();

                PopulateDevices();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void PopulateDevices()
        {
            try
            {
                if (conn == null)
                    return;

                if (conn.Status.ServerStatus == ServiioStatus.ServerStates.Started)
                {
                    checkBoxSharingStatus.Checked = true;
                    checkBoxSharingStatus.ImageIndex = 1;
                    checkBoxSharingStatus.Text = "Enabled";
                }
                else
                {
                    checkBoxSharingStatus.Checked = false;
                    checkBoxSharingStatus.ImageIndex = 0;
                    checkBoxSharingStatus.Text = "Disabled";
                }

                listViewDevices.SetObjects(conn.Status.Devices);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void EditDevice(ServiioDevice selectedDevice)
        {
            try
            {
                if (selectedDevice != null)
                {
                    DeviceDetailsForm dialog = new DeviceDetailsForm();
                    if (dialog.Edit(conn, selectedDevice))
                    {
                        conn.Status.Update();
                        RefreshDevices();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void RemoveDevice(ServiioDevice selectedDevice)
        {
            try
            {
                MessageBox.Show("HERE");
                if (selectedDevice != null)
                {
                    if (MessageBox.Show("Are you sure you want to remove this device?", "Remove confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;

                    conn.Status.Devices.Remove(selectedDevice);
                    conn.Status.Update();
                    RefreshDevices();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void LibraryScanActive(ServiioLibraryStatus status = null)
        {
            try
            {
                timerAnimate.Enabled = true;
                labelScanStatus.Text = "Updating library...";
                if (status != null && !string.IsNullOrEmpty(status.LastAddedFileName))
                    labelScanLastAdded.Text = "Added: " + status.LastAddedFileName;
                if (status != null && status.NumberOfAddedFiles > 0)
                    labelScanNumAdded.Text = "Total Added: " +status.NumberOfAddedFiles;
                timerLibraryStatus.Interval = 5000;
                buttonForceUpdate.Enabled = false;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void LibraryScanIdle()
        {
            try
            {
                timerAnimate.Enabled = false;
                labelScanStatus.Text = "Idle.";
                labelScanLastAdded.Text = "";
                labelScanNumAdded.Text = "";
                pictureBoxScanStatus.Image = imageList48.Images[0];
                timerLibraryStatus.Interval = 10000;
                buttonForceUpdate.Enabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private int currentScanImage = 0;
        private void timerAnimate_Tick(object sender, EventArgs e)
        {
            try
            {
                if (++currentScanImage > 8)
                    currentScanImage = 1;

                pictureBoxScanStatus.Image = imageList48.Images[currentScanImage];
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void timerLibraryStatus_Tick(object sender, EventArgs e)
        {
            try
            {
                if (conn == null)
                    return;

                ServiioLibraryStatus status = conn.GetLibraryStatus();
                if (status == null)
                    return;

                if (status.IsUpdatesCheckerRunning || status.IsAdditionsCheckerRunning)
                    LibraryScanActive(status);
                else
                    LibraryScanIdle();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                DeviceDetailsForm dialog = new DeviceDetailsForm();
                ServiioDevice newDevice = dialog.New(conn);
                if (newDevice != null)
                {
                    conn.Status.Devices.Add(newDevice);
                    conn.Status.Update();
                    RefreshDevices();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (listViewDevices.SelectedObject == null)
                    return;

                EditDevice((ServiioDevice)listViewDevices.SelectedObject);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (listViewDevices.SelectedObject == null)
                    return;

                RemoveDevice((ServiioDevice)listViewDevices.SelectedObject);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            RefreshDevices();
        }

        private void listViewDevices_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (listViewDevices.SelectedObject == null)
                    return;

                if (e.KeyChar == (char)Keys.Enter)
                    EditDevice((ServiioDevice)listViewDevices.SelectedObject);
                else if (e.KeyChar == (char)Keys.Delete)
                    RemoveDevice((ServiioDevice)listViewDevices.SelectedObject);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void listViewDevices_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                ListViewHitTestInfo hit = listViewDevices.HitTest(e.Location);
                if (hit.Item != null)
                {
                    listViewDevices.SelectedIndex = hit.Item.Index;
                    EditDevice((ServiioDevice)listViewDevices.SelectedObject);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonForceUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                conn.ForceLibraryRefresh();
                LibraryScanActive();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void checkBoxSharingStatus_Click(object sender, EventArgs e)
        {
            try
            {
                checkBoxSharingStatus.Text = "...wait...";
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();

                if (checkBoxSharingStatus.Checked)
                    conn.StartUpnpServer();
                else
                    conn.StopUpnpServer();

                RefreshDevices();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void panelLeftColumn_Paint(object sender, PaintEventArgs e)
        {
            GuiHelper.DrawBorder(e, panelLeftColumn, new GuiHelper.BorderSides(true, true, false, false));
        }

    }
}
